package com.springboot.frame.comm.database.registry;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map.Entry;

/**
 * @author madman
 */
public final class MysqlTypeRegistry extends AbstractTypeRegistry {

  public static final MysqlTypeRegistry INSTANCE = new MysqlTypeRegistry();

  public MysqlTypeRegistry() {
    registry(Integer.class, "tinyint", "smallint", "mediumint", "int", "integer");

    registry(Long.class, "bigint");

    registry(Float.class, "float");

    registry(Double.class, "double", "real");

    registry(BigDecimal.class, "decimal", "numeric");

    registry(String.class, "char", "varchar", "tinytext", "mediumtext", "text", "longtext");

    registry(Date.class, "date", "time", "datetime", "timestamp", "year");

    registry(Boolean.class, "bit", "boolean");

    registry(byte[].class, "tinyblob", "mediumblob", "longblob", "blob", "binary");
  }

  @Override
  public Class<?> getJavaType(String columnType) {
    Class<?> clazz = javaTypeRegistry
        .get(columnType.contains("(") ? columnType.substring(0, columnType.indexOf('('))
            : columnType);
    return clazz != null ? clazz : String.class;
  }

  public String getJdbcType(Class<?> clazz) {
    for (Entry<String, Class<?>> entry : javaTypeRegistry.entrySet()) {
      if (entry.getValue() == clazz) {
        return entry.getKey();
      }
    }
    return "varchar";
  }

}
